<template>
  <a-upload-dragger
    v-model:fileList="fileList"
    name="file"
    :multiple="true"
    :beforeUpload="beforeUpload"
    :headers="{ tokenSign: 2, userId, Authorization: token, accountId }"
    :action="url"
    @change="handleChange"
  >
    <p class="ant-upload-drag-icon">
      <inbox-outlined></inbox-outlined>
    </p>
    <p class="ant-upload-text">点击或将文件拖拽到这里上传</p>
    <p class="ant-upload-hint">文件支持扩展名：.xlsx .xls .csv .pdf .word</p>
  </a-upload-dragger>
</template>
<script>
import { InboxOutlined } from '@ant-design/icons-vue'
import { message } from 'ant-design-vue'
import { defineComponent, ref } from 'vue'
// import axios from 'axios'
const uploadURL = process.env.VUE_APP_ERP_IMG
export default defineComponent({
  components: {
    InboxOutlined
  },
  props: {
    size: {
      type: Number,
      default: 20
    },
    maxLength: {
      type: Number,
      default: 10
    },
    fileInfo: {
      type: Array,
      default: () => []
    }
  },
  emits: ['update:fileInfo', 'change'],
  setup(props, { emit }) {
    const url = ref(uploadURL)
    const fileList = ref([])
    const handleChange = info => {
      const status = info.file.status

      if (status !== 'uploading') {
        console.log(info.file, info.fileList)
      }

      if (status === 'done') {
        message.success(`${info.file.name} file uploaded successfully.`)
      } else if (status === 'error') {
        message.error(`${info.file.name} file upload failed.`)
      }
      const fileCopy = []
      fileList.value.forEach(_ => {
        console.log(_, fileCopy)
        if (_.response && _.response.success) {
          const { ossName, ossUrl, ossSuffix } = _.response.data
          fileCopy.push({
            name: ossName,
            ossName,
            ossUrl,
            ossSuffix,
            uid: Math.random()
          })
        } else {
          fileCopy.push(_)
        }
      })
      fileList.value = fileCopy
      emit('update:fileInfo', fileCopy)
    }
    const beforeUpload = file => {
      const sheet =
        file.type.endsWith('.sheet') ||
        file.type.endsWith('.pdf') ||
        file.name.endsWith('.word') ||
        file.name.endsWith('.docx')
      if (!sheet) {
        message.error(`File Only support .xlsx .xls .csv,pdf,word!`)
      }
      const len = fileList.value.lenth <= props.maxLength
      if (len) {
        message.error(` Upload up to ${props.maxLength} files !`)
      }
      const isLt2M = file.size / 1024 / 1024 < props.size
      if (!isLt2M) {
        message.error(`File must smaller than ${props.size}MB!`)
      }
      return new Promise((resolve, reject) => {
        return isLt2M && sheet && !len ? resolve() : reject()
      })
    }
    return {
      beforeUpload,
      url,
      fileList,
      token: localStorage.token,
      userId: localStorage.userId,
      accountId: localStorage.accountId,
      handleChange
    }
  }
})
</script>
